#include "SettingBoard.h"
#include "DataManage.h"
#include "AchievementManage.h"
#include "HelpBoard.h"
#include "AudioManage.h"
#include "CardSprite.h"

static const char* BUTTON_CLOSE = "SettingBoard/help_exit.png";
static const char* BUTTON_HELP = "OperateBoard/button_red.png";

ShowCardNode* ShowCardNode::create(int nType)
{
	ShowCardNode *pRet = new(std::nothrow) ShowCardNode();
	if (pRet && pRet->init(nType))
	{
		pRet->autorelease();
		return pRet;
	}
	else
	{
		delete pRet;
		pRet = nullptr;
		return nullptr;
	}
}

bool ShowCardNode::init(int nType)
{
	if (!Node::init())
	{
		return false;
	}

	m_pBase = Sprite::create("SettingBoard/showCardBase.png");
	addChild(m_pBase);

	m_nType = nType;
	updateContent();

	auto listener1 = EventListenerTouchOneByOne::create();
	listener1->setSwallowTouches(true);
	listener1->onTouchBegan = [this](Touch* touch, Event* event)
	{
		removeFromParent();
		return true;
	};

	_eventDispatcher->addEventListenerWithSceneGraphPriority(listener1, this);
	return true;
}

void ShowCardNode::updateContent()
{
	Size baseSize = m_pBase->getContentSize();

	int nCardCount = m_nType == HOURSE ? 30 : 16;
	if (m_nType == HOURSE)
	{
		for (int i = 0; i < nCardCount; i++)
		{
			int nCol = i % 8;
			int nRow = i / 8;

			CardSprite* pShowCard = CardSprite::create(m_nType - 2, i + 1);
			pShowCard->setScale(0.15f);
			pShowCard->setPosition(baseSize.width / 9 * (nCol + 1), baseSize.height / 5 * (3.8f - nRow));
			m_pBase->addChild(pShowCard);
			pShowCard->showCard();

			if (AchievementManage::getInstance()->checkHourseCardHasGot(i+1) == false)
			{
				pShowCard->turnToBlackWhite();
			}
		}
	}
	else
	{
		for (int i = 0; i < nCardCount; i++)
		{
			int nCol = i == 0 ? 0 : (i - 1) % 5;
			int nRow = i == 0 ? 0 : (i - 1) / 5;

			if (i == 1)
			{
				continue;
			}

			CardSprite* pShowCard = CardSprite::create(m_nType - 2, i);
			pShowCard->setScale(0.2f);
			pShowCard->setPosition(baseSize.width / 6 * (nCol + 1), baseSize.height / 4 * (2.9f - nRow));
			m_pBase->addChild(pShowCard);
			pShowCard->showCard();

			if (AchievementManage::getInstance()->checkMoneyCardHasGot(i) == false)
			{
				pShowCard->turnToBlackWhite();
			}
		}
	}
}

int SoundsNode::s_nSoundIndex(9);
int SoundsNode::s_nMusicIndex(9);

SoundsNode* SoundsNode::create(unsigned int nType)
{
	SoundsNode *pRet = new(std::nothrow) SoundsNode();
	if (pRet && pRet->init(nType))
	{ 
		pRet->autorelease(); 
		return pRet; 
	} 
	else 
	{ 
		delete pRet; 
		pRet = nullptr; 
		return nullptr; 
	} 
}

bool SoundsNode::init(unsigned int nType)
{
	if (!Node::init())
	{
		return false;
	}

	m_nType = nType;

	Sprite* pNodeBase = Sprite::create("SettingBoard/soundBase.png");
	pNodeBase->setPosition(Point::ZERO);
	addChild(pNodeBase);

	string strSoundsPath = "";

	if (nType == SOUNDS)
	{
		strSoundsPath = __String::createWithFormat("SettingBoard/sound.png")->getCString();
		m_nCurrentMarkIndex = s_nSoundIndex;
	}
	else
	{
		strSoundsPath = __String::createWithFormat("SettingBoard/music.png")->getCString();
		m_nCurrentMarkIndex = s_nMusicIndex;
	}

	for (int i = 0; i < 10; i++)
	{
		Sprite* pMark = Sprite::create("OperateBoard/buy_money_note.png");
		pMark->setPosition(pNodeBase->getContentSize().width * 0.16f + 17 * i, pNodeBase->getContentSize().height / 2);
		pNodeBase->addChild(pMark);

		m_rgMarks.pushBack(pMark);
		if (i > m_nCurrentMarkIndex)
		{
			pMark->setVisible(false);
		}
	}

	m_pSoundButton = MenuItemImage::create(strSoundsPath, strSoundsPath, CC_CALLBACK_0(SoundsNode::onSoundButtonClick, this));
	m_pSoundButton->setPosition(pNodeBase->getContentSize().width  * -0.9f, 0);
	m_pSoundButton->setScale(1.7f);

	string strAddPath = "OperateBoard/button_add.png";
	MenuItemImage* pAddButton = MenuItemImage::create(strAddPath, strAddPath, CC_CALLBACK_0(SoundsNode::onAddButtonClick, this));
	pAddButton->setPosition(pNodeBase->getContentSize().width  * 0.6f, 0);

	string strSubPath = "OperateBoard/button_sub.png";
	MenuItemImage* pSubButton = MenuItemImage::create(strSubPath, strSubPath, CC_CALLBACK_0(SoundsNode::onSubButtonClick, this));
	pSubButton->setPosition(pNodeBase->getContentSize().width  * -0.6f, 0);

	Menu* pButtonsMenu = Menu::create(m_pSoundButton, pAddButton, pSubButton, nullptr);
	pButtonsMenu->setPosition(Point::ZERO);
	addChild(pButtonsMenu);

	return true;
}

void SoundsNode::onAddButtonClick()
{
	m_nCurrentMarkIndex++;
	if (m_nCurrentMarkIndex == m_rgMarks.size())
	{
		m_nCurrentMarkIndex--;
	}

	for (int i = 0; i < (int)m_rgMarks.size(); i++)
	{
		if (i <= m_nCurrentMarkIndex)
		{
			m_rgMarks.at(i)->setVisible(true);
		}
		else
		{
			m_rgMarks.at(i)->setVisible(false);
		}
	}

	float flPercent = (float)m_nCurrentMarkIndex / (float)m_rgMarks.size();
	if (m_nType == SOUNDS)
	{
		AudioManage::setEffectSound(flPercent);
		s_nSoundIndex = m_nCurrentMarkIndex;
	}
	else
	{
		AudioManage::setMusicSound(flPercent);
		s_nMusicIndex = m_nCurrentMarkIndex;
	}
}

void SoundsNode::onSubButtonClick()
{
	m_nCurrentMarkIndex--;
	if (m_nCurrentMarkIndex < 0)
	{
		m_nCurrentMarkIndex = 0;
	}

	for (int i = 0; i < (int)m_rgMarks.size(); i++)
	{
		if (i <= m_nCurrentMarkIndex)
		{
			m_rgMarks.at(i)->setVisible(true);
		}
		else
		{
			m_rgMarks.at(i)->setVisible(false);
		}
	}

	float flPercent = (float)m_nCurrentMarkIndex / (float)m_rgMarks.size();
	if (m_nType == SOUNDS)
	{
		AudioManage::setEffectSound(flPercent);
		s_nSoundIndex = m_nCurrentMarkIndex;
	}
	else
	{
		AudioManage::setMusicSound(flPercent);
		s_nMusicIndex = m_nCurrentMarkIndex;
	}
}

void SoundsNode::onSoundButtonClick()
{
	string strSoundsPath = "";

	if (m_bIsMute)
	{
		m_bIsMute = false;
		strSoundsPath = __String::createWithFormat(m_nType == SOUNDS ? "SettingBoard/sound.png" : "SettingBoard/music.png")->getCString();
	}
	else
	{
		m_bIsMute = true;
		strSoundsPath = __String::createWithFormat(m_nType == SOUNDS ? "SettingBoard/sound2.png" : "SettingBoard/music2.png")->getCString();
	}

	m_pSoundButton->setNormalImage(Sprite::create(strSoundsPath));
	m_pSoundButton->setSelectedImage(Sprite::create(strSoundsPath));
}

bool SettingBoard::init()
{
	if (!Layer::init())
	{
		return false;
	}

	Size viewSize = Director::getInstance()->getVisibleSize();

	LayerColor* pBaseColor = LayerColor::create(Color4B(0, 0, 0, 150), viewSize.width * 2, viewSize.height * 2);
	pBaseColor->setPosition(viewSize.width / 2 * -1, viewSize.height / 2 * -1);
	addChild(pBaseColor);

	Sprite* pBoardBaseSprite = Sprite::create("SettingBoard/settingBase.png");
	pBoardBaseSprite->setPosition(viewSize.width / 2, viewSize.height * 0.5f);
	addChild(pBoardBaseSprite);

	m_pBoardBaseSprite = pBoardBaseSprite;

	Sprite* pTitleSprite = Sprite::create("SettingBoard/fontSetting.png");
	pTitleSprite->setPosition(pBoardBaseSprite->getContentSize().width / 2, pBoardBaseSprite->getContentSize().height * 0.92f);
	pBoardBaseSprite->addChild(pTitleSprite);

	float flTitleOffsetY = 18.0f;
	float flTitleScale = 1.2f;

	// Icons
	Sprite* pIconBase = Sprite::create("SettingBoard/iconBase.png");
	pIconBase->setAnchorPoint(Point(0.5f, 1.0f));
	pIconBase->setPosition(pBoardBaseSprite->getContentSize().width / 2, pBoardBaseSprite->getContentSize().height * 0.87f);
	pBoardBaseSprite->addChild(pIconBase);

	Sprite* pIconTitle = Sprite::create("SettingBoard/fontIcons.png");
	pIconTitle->setPosition(pBoardBaseSprite->getContentSize().width * 0.1f, pIconBase->getPositionY() + flTitleOffsetY);
	pIconTitle->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT);
	pIconTitle->setScale(flTitleScale);
	pBoardBaseSprite->addChild(pIconTitle);

	Sprite* pIconFontBase = Sprite::create("SettingBoard/iconsFontsBase.png");
	pIconFontBase->setPosition(pIconBase->getContentSize().width * 0.5f, pIconBase->getContentSize().height * 0.22f);
	pIconBase->addChild(pIconFontBase);

	m_pIconMark = Sprite::create("SettingBoard/ok.png");
	int nCurrentIconIndex = AchievementManage::getInstance()->getCurrentIconIndex();
	m_pIconMark->setPosition(pBoardBaseSprite->getContentSize().width * 0.2f + nCurrentIconIndex % 4 * 115 + 40,
							 pBoardBaseSprite->getContentSize().height * (0.8f - (nCurrentIconIndex / 4) * 0.11f) - 40);
	pBoardBaseSprite->addChild(m_pIconMark, 1);

	m_pIconDescMark = Sprite::create("SettingBoard/arrow.png");
	m_pIconDescMark->setScale(0.5f);
	m_pIconDescMark->setPosition(pBoardBaseSprite->getContentSize().width * 0.2f + nCurrentIconIndex % 4 * 115,
		pBoardBaseSprite->getContentSize().height * (0.8f - (nCurrentIconIndex / 4) * 0.11f) + 60);
	pBoardBaseSprite->addChild(m_pIconDescMark, 1);

	ActionInterval* pMoveDown = MoveBy::create(0.5f, Point(0, -20.0f));
	ActionInterval* pMoveUp = MoveBy::create(0.5f, Point(0, 20));
	ActionInterval* pMoveAction = Sequence::create(pMoveDown, pMoveUp, nullptr);

	ActionInterval* pScaleWider = ScaleTo::create(0.5f, 1.5 * 0.5f, 0.5);
	ActionInterval* pScaleThiner = ScaleTo::create(0.5f, 1.2 * 0.5f, 0.5);
	ActionInterval* pScaleAction = Sequence::create(pScaleWider, pScaleThiner, nullptr);

	m_pIconDescMark->runAction(RepeatForever::create(Spawn::create( pMoveAction, pScaleAction, nullptr)));

	string strIconDescPath = __String::createWithFormat("SettingBoard/icon%dDesc.png", nCurrentIconIndex + 1)->getCString();
	m_pIconDesc = Sprite::create(strIconDescPath);
	m_pIconDesc->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT);
	m_pIconDesc->setPosition(pIconFontBase->getContentSize().width * 0.05f, pIconFontBase->getContentSize().height * 0.65f);
	pIconFontBase->addChild(m_pIconDesc);

	m_pIconLabel = Label::createWithTTF("", "fonts/arial.ttf", 30);
	m_pIconLabel->setTextColor(Color4B::WHITE);
	m_pIconLabel->enableOutline(Color4B::GRAY);
	m_pIconLabel->setAnchorPoint(Point::ANCHOR_MIDDLE_RIGHT);
	m_pIconLabel->setPosition(pIconFontBase->getContentSize().width * 0.9f, pIconFontBase->getContentSize().height * 0.3f);
	pIconFontBase->addChild(m_pIconLabel);

	// Sounds
	Sprite* pSoundsBase = Sprite::create("SettingBoard/soundsBase.png");
	pSoundsBase->setAnchorPoint(Point(0.5f, 1.0f));
	pSoundsBase->setPosition(pBoardBaseSprite->getContentSize().width / 2, pBoardBaseSprite->getContentSize().height * 0.44f);
	pBoardBaseSprite->addChild(pSoundsBase);

	Sprite* pSoundsTitle = Sprite::create("SettingBoard/fontSounds.png");
	pSoundsTitle->setPosition(pBoardBaseSprite->getContentSize().width * 0.1f, pSoundsBase->getPositionY() + flTitleOffsetY);
	pSoundsTitle->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT);
	pSoundsTitle->setScale(flTitleScale);
	pBoardBaseSprite->addChild(pSoundsTitle);

	Sprite* pSoundsContentBase = Sprite::create("SettingBoard/soundsBaseBase.png");
	pSoundsContentBase->setPosition(pSoundsBase->getContentSize().width / 2, pSoundsBase->getContentSize().height / 2);
	pSoundsBase->addChild(pSoundsContentBase);

	SoundsNode* pSoundNode = SoundsNode::create(SoundsNode::SOUNDS);
	pSoundNode->setPosition(pSoundsContentBase->getContentSize().width / 2 + 35, pSoundsContentBase->getContentSize().height / 3 * 2 + 5);
	pSoundsContentBase->addChild(pSoundNode);

	SoundsNode* pMusicNode = SoundsNode::create(SoundsNode::MUSIC);
	pMusicNode->setPosition(pSoundsContentBase->getContentSize().width / 2 + 35, pSoundsContentBase->getContentSize().height / 3 - 5);
	pSoundsContentBase->addChild(pMusicNode);

	// Help
	Sprite* pHelpBase = Sprite::create("SettingBoard/helpBase.png");
	pHelpBase->setAnchorPoint(Point(0.5f, 1.0f));
	pHelpBase->setPosition(pBoardBaseSprite->getContentSize().width / 2, pBoardBaseSprite->getContentSize().height * 0.2f);
	pBoardBaseSprite->addChild(pHelpBase);

	Sprite* pHelpTitle = Sprite::create("SettingBoard/fontHelp.png");
	pHelpTitle->setPosition(pBoardBaseSprite->getContentSize().width * 0.1f, pHelpBase->getPositionY() + flTitleOffsetY);
	pHelpTitle->setAnchorPoint(Point::ANCHOR_MIDDLE_LEFT);
	pHelpTitle->setScale(flTitleScale);
	pBoardBaseSprite->addChild(pHelpTitle);

	Sprite* pHelpDesc = Sprite::create("SettingBoard/fontHelpDesc.png");
	pHelpDesc->setPosition(pHelpBase->getContentSize().width * 0.4f, pHelpBase->getContentSize().height / 2);
	pHelpBase->addChild(pHelpDesc);

	// Buttons
	Vector<MenuItem*> rgArrayOfItems;

	MenuItem* pCloseButton = MenuItemImage::create(BUTTON_CLOSE, BUTTON_CLOSE, CC_CALLBACK_0(SettingBoard::onCloseButtonClick, this));
	pCloseButton->setPosition(pBoardBaseSprite->getContentSize().width * 0.90f, pBoardBaseSprite->getContentSize().height * 0.935f);
	pCloseButton->setScale(1.5f);
	rgArrayOfItems.pushBack(pCloseButton);

	for (int i = 0; i < 8; i++)
	{
		string strIconPath = __String::createWithFormat("SettingBoard/PlayerIcon%d.png", i + 1)->getCString();
		MenuItemImage* pIconButton = MenuItemImage::create(strIconPath, strIconPath, CC_CALLBACK_0(SettingBoard::onIconClick, this, i));
		pIconButton->setPosition(pBoardBaseSprite->getContentSize().width * 0.2f + i % 4 * 115, 
								 pBoardBaseSprite->getContentSize().height * (0.8f - (i / 4) * 0.11f));

		if (AchievementManage::getInstance()->checkIconCanUse(i) == false)
		{
			Sprite* pBlackIcon = Sprite::create(strIconPath);

			auto fileUtiles = FileUtils::getInstance();
			auto fragmentGrayFullPath = fileUtiles->fullPathForFilename("Card/grayNew.fsh");
			auto fragSource = fileUtiles->getStringFromFile(fragmentGrayFullPath);
			auto glprogram = GLProgram::createWithByteArrays(ccPositionTextureColor_noMVP_vert, fragSource.c_str());
			GLProgramState* grayGLProgrameState = GLProgramState::getOrCreateWithGLProgram(glprogram);
			grayGLProgrameState->retain();
			pBlackIcon->setGLProgramState(grayGLProgrameState);

			pIconButton->setNormalImage(pBlackIcon);
		}

		rgArrayOfItems.pushBack(pIconButton);
	}

	MenuItem* pHelpButton = MenuItemImage::create(BUTTON_HELP, BUTTON_HELP, CC_CALLBACK_0(SettingBoard::onHelpButtonClick, this));
	pHelpButton->setPosition(pBoardBaseSprite->convertToNodeSpace(pHelpBase->convertToWorldSpace(Point(pHelpBase->getContentSize().width * 0.8f, pHelpBase->getContentSize().height / 2))));
	rgArrayOfItems.pushBack(pHelpButton);

	Label* pHelpLabel = Label::createWithTTF("Help", "fonts/arial.ttf", 25);
	pHelpLabel->setTextColor(Color4B::WHITE);
	//pHelpLabel->enableBold();
	pHelpLabel->setPosition(Point(pHelpButton->getContentSize().width / 2, pHelpButton->getContentSize().height / 2 + 7));
	pHelpButton->addChild(pHelpLabel);

	Menu* pButtonMenu = Menu::createWithArray(rgArrayOfItems);
	pButtonMenu->setPosition(Point::ZERO);
	pBoardBaseSprite->addChild(pButtonMenu);
    
	refreshLabel(nCurrentIconIndex);

	setTouchMode(Touch::DispatchMode::ONE_BY_ONE);
	setTouchEnabled(true);
	setSwallowsTouches(true);
    
	return true;
}

void SettingBoard::onCloseButtonClick()
{
	AudioManage::button2Sound();
	removeFromParent();
}


void SettingBoard::onHelpButtonClick()
{
	AudioManage::button1Sound();
	Size viewSize = Director::getInstance()->getVisibleSize();

	HelpBoard* pHelpBoard = HelpBoard::create();
	pHelpBoard->setScale(0.5f);
	Director::getInstance()->getRunningScene()->addChild(pHelpBoard);

	removeFromParent();
}

void SettingBoard::onIconClick(int nIconIndex)
{
	int nCurrentIconIndex = nIconIndex;

	if (AchievementManage::getInstance()->checkIconCanUse(nIconIndex) == true)
	{
		m_pIconMark->setPosition(m_pBoardBaseSprite->getContentSize().width * 0.2f + nCurrentIconIndex % 4 * 115 + 40,
			m_pBoardBaseSprite->getContentSize().height * (0.8f - (nCurrentIconIndex / 4) * 0.11f) - 40);

		AchievementManage::getInstance()->setCurrentIconIndex(nIconIndex);
		AudioManage::buttonSound();
	}
	else
	{
		AudioManage::wrongSound();
	}

	ActionInterval* pMoveDown = MoveBy::create(0.5f, Point(0, -20.0f));
	ActionInterval* pMoveUp = MoveBy::create(0.5f, Point(0, 20));
	ActionInterval* pMoveAction = Sequence::create(pMoveDown, pMoveUp, nullptr);

	ActionInterval* pScaleWider = ScaleTo::create(0.5f, 1.5 * 0.5f, 0.5f);
	ActionInterval* pScaleThiner = ScaleTo::create(0.5f, 1.2 * 0.5f, 0.5f);
	ActionInterval* pScaleAction = Sequence::create(pScaleWider, pScaleThiner, nullptr);

	m_pIconDescMark->setPosition(m_pBoardBaseSprite->getContentSize().width * 0.2f + nCurrentIconIndex % 4 * 115,
		m_pBoardBaseSprite->getContentSize().height * (0.8f - (nCurrentIconIndex / 4) * 0.11f) + 60);
	m_pIconDescMark->stopAllActions();
	m_pIconDescMark->runAction(RepeatForever::create(Spawn::create(pMoveAction, pScaleAction, nullptr)));

	string strIconDescPath = __String::createWithFormat("SettingBoard/icon%dDesc.png", nCurrentIconIndex + 1)->getCString();
	m_pIconDesc->setTexture(strIconDescPath);

	refreshLabel(nIconIndex);

	if (nIconIndex == 2 || nIconIndex == 3)
	{
		Size viewSize = Director::getInstance()->getVisibleSize();

		ShowCardNode* pShowCard = ShowCardNode::create(nIconIndex);
		pShowCard->setPosition( viewSize.width / 2, viewSize.height * 0.12f );
		addChild(pShowCard);
	}
}

bool SettingBoard::onTouchBegan(Touch *touch, Event *event)
{
	return true;
}

void SettingBoard::refreshLabel(int nIconIndex)
{
	if (nIconIndex == 0)
	{
		m_pIconLabel->setVisible(false);
	}
	else
	{
		m_pIconLabel->setVisible(true);
	}

	int nValue = AchievementManage::getInstance()->getCurrentValue(nIconIndex);
	if (nIconIndex == 2)
	{
		m_pIconLabel->setString(__String::createWithFormat("Current: %d/30", nValue)->getCString());
	}
	else if (nIconIndex == 3)
	{
		m_pIconLabel->setString(__String::createWithFormat("Current: %d/15", nValue)->getCString());
	}
	else if (nIconIndex == 6 || nIconIndex == 7)
	{
		m_pIconLabel->setString(__String::createWithFormat("Current: $%d,000", nValue)->getCString());

		if (nValue >= 1000)
		{
			int nK = nValue / 1000;
			int nS = nValue - nK * 1000;

			m_pIconLabel->setString(__String::createWithFormat("Current: $%d,%.3d,000", nK, nS)->getCString());
		}
	}
	else
	{
		m_pIconLabel->setString(__String::createWithFormat("Current: %d", nValue)->getCString());
	}
}
